package com.dalongxin.work.page;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.TypedValue;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.andview.refreshview.XRefreshView;
import com.andview.refreshview.XRefreshViewFooter;
import com.andview.refreshview.utils.LogUtils;
import com.dalongxin.work.Constants;
import com.dalongxin.work.R;
import com.dalongxin.work.data.CloudDisk;
import com.dalongxin.work.page.adapter.CloudDiskAdapter;
import com.dalongxin.work.utils.HttpUtil;
import com.dalongxin.work.utils.StatusUtils;

import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Stack;

/**
 * Created by zhaoyu on 2017/9/6.
 * 选择目标文件夹页面
 */
@ContentView(R.layout.activity_cloud_disk_choose_folder)
public class CloudDiskChooseFolderActivity extends BaseActivity {

    private static final String TAG = "CloudDiskChooseFolderActivity";
    public static final int MOVE_REQUEST_CODE = 1021;
    public static final int MOVE_CLOUD_DISK_FRAGMENT_RESULT_CODE = 1022;
    public static final int MOVE_SEARCH_ACTIVITY_RESULT_CODE = 1023;
    private int mPage = 1;
    private String mClassId;

    @ViewInject(R.id.recycler_view)
    private RecyclerView recyclerView;
    @ViewInject(R.id.xrefreshview)
    private XRefreshView xRefreshView;

    private List<CloudDisk> mDatas = new ArrayList<>();
    private CloudDiskAdapter mAdapter;
    private View mNoDataImg;
    private String mFolderIds;
    private String mCurrFolder;
    private Stack<String> mFolderStack = new Stack<>(); //文件夹栈

    public void setCurrFolder(String currFolder) {
        mCurrFolder = currFolder;
        mFolderStack.push(currFolder);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);
        setTitle(R.string.cloud_disk_title);
        mCurrFolder = "-1";
        mFolderStack.push("-1");
        findViewById(R.id.title_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mFolderStack.size() > 1) {
                    mFolderStack.pop();
                    mCurrFolder = mFolderStack.peek();
                    getTargetFolderList();
                } else {
                    finish();
                }
            }
        });

        Button cancelTv = findViewById(R.id.title_menu);
        cancelTv.setText("取消");
        cancelTv.setVisibility(View.VISIBLE);
        cancelTv.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.dp_15));
        int padding14 = (int) getResources().getDimension(R.dimen.dp_14);
        int padding7 = (int) getResources().getDimension(R.dimen.dp_7);
        int padding6 = (int) getResources().getDimension(R.dimen.dp_6);
        cancelTv.setPadding(padding14, padding7, 0, padding6);
        cancelTv.setBackgroundColor(getResources().getColor(R.color.transparent));
        cancelTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        String fileIds = getIntent().getStringExtra("fileIds");
        mFolderIds = getIntent().getStringExtra("folderIds");
        mClassId = getIntent().getStringExtra("classId");

        mAdapter = new CloudDiskAdapter(this, this, mDatas);
        mAdapter.setFileIds(fileIds);
        mAdapter.setFolderIds(mFolderIds);

        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL));
        // 静默加载模式不能设置footerview
        recyclerView.setAdapter(mAdapter);
        //设置刷新完成以后，headerview固定的时间
        xRefreshView.setPinnedTime(1000);
        xRefreshView.setMoveForHorizontal(true);
        //xRefreshView1.setAutoLoadMore(true);
        mAdapter.setCustomLoadMoreView(new XRefreshViewFooter(this));
        //设置静默加载时提前加载的item个数
        //xRefreshView1.setPreLoadCount(4);
        xRefreshView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {

            @Override
            public void onRefresh(boolean isPullDown) {
                mPage = 1;
                getTargetFolderList();
            }

            @Override
            public void onLoadMore(boolean isSilence) {
                mPage++;
                getTargetFolderList();
            }
        });
        xRefreshView.setPullRefreshEnable(true);//允许下拉刷新
        xRefreshView.setPullLoadEnable(false);//禁止加载更多
        xRefreshView.setAutoRefresh(true);
        mNoDataImg = findViewById(R.id.image_no_data);
    }

    public void getTargetFolderList() {
        HashMap<String, String> params = new HashMap<>();
        params.put("folderId", mCurrFolder);
        //params.put("selectFolderId", mFolderIds);
        //params.put("page", mPage+"");
        LogUtils.i(TAG + " getfolderList 接口参数：\n" + params.toString());
        HttpUtil.getInstance().post(true, Constants.url_getMyFolderList, params, new Callback.CommonCallback<JSONObject>() {
            @Override
            public void onSuccess(JSONObject response) {
                LogUtils.i(TAG + " getfolderList 接口返回：\n" + response.toString());
                xRefreshView.stopRefresh();
                if (response.optInt("ret") == 0) {
                    try {
                        List<CloudDisk> datas = CloudDisk.parseFolderFromJsonList(response.optJSONArray("data"), true);
                        if (mPage == 1) {
                            mDatas.clear();
                        }
                        if (datas != null && datas.size() > 0) {
                            mNoDataImg.setVisibility(View.GONE);
                            mDatas.addAll(datas);
                            mAdapter.notifyDataSetChanged();
                        } else {
                            if (mPage == 1) {
                                mDatas.clear();
                                mAdapter.notifyDataSetChanged();
                                mNoDataImg.setVisibility(View.VISIBLE);
                            } else {
                                mPage--;
                                Toast.makeText(CloudDiskChooseFolderActivity.this, "已经到底了", Toast.LENGTH_SHORT).show();
                                xRefreshView.stopRefresh();
                            }
                        }
                    } catch (Exception ex) {

                    }
                } else {
                    StatusUtils.handleStatus(response, CloudDiskChooseFolderActivity.this);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                if (mPage > 1) {
                    mPage--;
                }
                xRefreshView.stopRefresh();
                StatusUtils.handleError(ex, CloudDiskChooseFolderActivity.this);
            }

            @Override
            public void onCancelled(CancelledException cex) {
                if (mPage > 1) {
                    mPage--;
                }
                xRefreshView.stopRefresh();
            }

            @Override
            public void onFinished() {
                hideLoading();
            }
        });
    }

    public static Intent newIntent(Context ctx, String fileIds, String folderIds) {
        Intent intent = new Intent(ctx, CloudDiskChooseFolderActivity.class);
        intent.putExtra("fileIds", fileIds);
        intent.putExtra("folderIds", folderIds);
        return intent;
    }

    public static Intent newIntent(Context ctx, String fileIds, String folderIds, String classId, boolean isFromSearchPage) {
        Intent intent = new Intent(ctx, CloudDiskChooseFolderActivity.class);
        intent.putExtra("fileIds", fileIds);
        intent.putExtra("folderIds", folderIds);
        intent.putExtra("classId", classId);
        intent.putExtra("isFromSearchPage", isFromSearchPage);
        return intent;
    }

    public void finishMoving() {
        if (getIntent().getBooleanExtra("isFromSearchPage", false)) {
            setResult(MOVE_SEARCH_ACTIVITY_RESULT_CODE);
        } else {
            setResult(MOVE_CLOUD_DISK_FRAGMENT_RESULT_CODE);
        }
        finish();
    }

}
